import axios from 'axios'
import { Toast } from 'vant'
import { Dialog } from 'vant'
import errorCode from '@/utils/errorCode'
import { getAppToken, loginOut } from '@/utils/app'
import { getToken } from '@/utils/auth'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 10000
})
// request拦截器
service.interceptors.request.use(config => {
  if (config.useToken == true) {
    try {
      // 是否需要设置 token
      let token = getAppToken()
      //token = 'eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2lkX2tleSI6IjI3M2U5ODQ2NTUwZDRhMjVlMWI3MTM3M2VlZGQxZGI2IiwibG9naW5fdXNlcl9rZXkiOiJiMGIwMDE4MS0zZjZhLTQ1ZGUtODUyNy1iMjllM2EwY2Y3N2UifQ.HGcOW5XHnIKZ0JCSFpO7NAi3tkQ-Ot52py7XlDUsrLemexUu-SEy-ebOHXkBbDXtK1FuK7bZUZ68THRr90CoGQ'
      if (token != null && token != '') {
        config.headers['token'] = token
      }
    } catch (e) {
    }
  }
  return config
}, error => {
  console.log(error)
  Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 0
    // 获取错误信息
    const msg = res.data.msg || errorCode[code] || errorCode['default']
    if (code === -1) {
      Dialog.alert({
        title: '系统提示',
        message: '登录状态已过期，请重新登录'
      }).then(() => {
        loginOut()
      })
    } else if (code === 1) {
      Toast({
        message: msg,
        position: 'bottom'
      })
      return Promise.reject(new Error(msg))
    } else if (code !== 0) {
      Toast({
        message: msg,
        position: 'bottom'
      })
      return Promise.reject('error')
    } else {
      return res.data
    }
  },
  error => {
    console.log('err' + error)
    let { message } = error
    if (message == 'Network Error') {
      message = '接口连接异常'
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时'
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常'
    }
    Toast({
      message: message,
      position: 'bottom'
    })
    return Promise.reject(error)
  }
)

export default service
